function hasClass(obj, cls) {
	return obj.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}

function addClass(obj, cls) {
	if (!this.hasClass(obj, cls)) obj.className += " " + cls;
}

function removeClass(obj, cls) {
	if (hasClass(obj, cls)) {
		var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
		obj.className = obj.className.replace(reg, ' ');
	}
}


var storage = window.localStorage;
var rec_dict = {},
	rec_array = [];
if ('rec_dict' in storage) {
	rec_dict = JSON.parse(storage['rec_dict']);
}
if ('rec_array' in storage) {
	rec_array = JSON.parse(storage['rec_array']);
}

var current_size = 0;
var screen_width;
var topic_id;
var topic_name;
var storage = window.localStorage;

var load_video = function(url, ele) {
	ele.removeAttribute('data-src');
	mui.getJSON('http://t.fanheapp.com/get_video', {
		url: url
	}, function(response) {
		if (response.success) {
			var video_url = response.data.video;
			ele.setAttribute('src', video_url);
		} else {
			console.log('load error for url:' + url);
		}
	});
}

var refresh_src = function() {
	mui("video").each(function() {
		var url = this.getAttribute('data-src');
		var src = this.getAttribute('src');
		if (url) {
			console.log("Load Video Url: " + url)
			load_video(url, this);
		}
	});
}

var collect = function(ele) {
	var img_ele = ele.getElementsByTagName('img')[0];
	var value_ele = ele.getElementsByTagName('span')[0];
	var value = parseInt(value_ele.innerText);
	value_ele.innerText = '' + (value + 1);
	img_ele.setAttribute('src', 'img/icon_like_green.png');

	addClass(ele, 'like');

	var frame_id = ele.getAttribute('data-id');
	var frame_ele = ele.parentNode.parentNode.parentNode;
	var frame = {
		'cover': frame_ele.getAttribute('data-cover'),
		'topic_name': topic_name,
		'frame_name': frame_ele.getAttribute('data-name'),
		'author': frame_ele.getAttribute('data-author'),
		'avatar': frame_ele.getAttribute('data-avatar'),
	};
	rec_dict[frame_id] = frame;
	rec_array = rec_array.reverse();
	rec_array.push(frame);
	rec_array.reverse();

	storage['rec_dict'] = JSON.stringify(rec_dict);
	storage['rec_array'] = JSON.stringify(rec_array);
	var frame_obj = new Frame();
	frame_obj.id = frame_id;
	frame_obj.increment('recCounter');
	frame_obj.save();
}

var un_collect = function(ele) {
	var img_ele = ele.getElementsByTagName('img')[0];
	var value_ele = ele.getElementsByTagName('span')[0];
	var value = parseInt(value_ele.innerText);
	value_ele.innerText = '' + (value - 1);
	img_ele.setAttribute('src', 'img/icon_like.png');
	removeClass(ele, 'like');
}

var appid = 'kou72um0ioak1kubrz0klwx8a7s3l261mgt54vbyotnblnby';
var appkey = 'o56bexx1vr522x7ygfkvi7efvbhhmo6x2oaf3txb75wi2509';
AV.initialize(appid, appkey);
var Topic = AV.Object.extend('Topic');
var Frame = AV.Object.extend('Frame');
var Lottery = AV.Object.extend('Lottery');
var Recommendation = AV.Object.extend('Recommendation');
mui.init({
	swipeBack: true,
	pullRefresh: {
		container: '#refreshContainer',
		deceleration: 0.0008,
		up: {
			callback: function() {
				var _this = this;
				var topic = new Topic();
				topic.id = topic_id;
				var frame_query = new AV.Query(Frame);
				frame_query.equalTo('topic', topic);
				frame_query.ascending('index');
				frame_query.addDescending('recCounter');
				frame_query.addDescending('createdAt');
				frame_query.limit(20);
				frame_query.skip(current_size);
				console.log(current_size);
				frame_query.find().then(function(objs) {
					current_size += objs.length;
					var frames_data = [];
					for (var i = 0; i < objs.length; i++) {
						var meta_data = JSON.parse(objs[i].get('metaDataV2'));
						var title = objs[i].get('head');
						if (title == null || title == undefined) {
							title = meta_data.title
						}

						var text = objs[i].get('content');
						if (text == null || text == undefined) {
							text = meta_data.text;
						}
						
						var content = meta_data.content;
						var imgs = [],
							long_tags = [],
							gif_tags = [];
						var video_covers = [];
						var cover_width = null,
							cover_height = null;
						for (var j = 0; j < content.length; j++) {
							if (content[j].type == 'photo' || content[j].type == 'gif') {
								var img_url = content[j].upyunUrl;
								imgs.push(img_url);
								long_tags.push(content[j].rawHeight / content[j].rawWidth > 2);
								gif_tags.push(content[j].type == 'gif');
							} else if (content[j].type == 'video') {
								var img_url = content[j].coverUrl;
								video_covers.push(img_url);
							}
						}
						var cover = objs[i].get('coverUrl');

						var is_long = long_tags.length > 0 ? long_tags[0] : false;
						if (cover == null || cover == undefined || cover == '') {
							if (imgs.length > 0) {
								cover = imgs[0];
							} else if (video_covers.length > 0) {
								cover = video_covers[0];
							}
						}

						var single_frame_data = {
							width: screen_width,
							id: objs[i].id,
							style: objs[i].get('style'),
							url: objs[i].get('url'),
							title: title,
							text: text,
							author: objs[i].get('author'),
							rec: objs[i].get('title'),
							rec_count: objs[i].get('recCounter'),
							cover: cover,
							is_long: is_long,
							imgs: imgs,
							meta_data: meta_data,
							liked: (objs[i].id in rec_dict),
							long_tags: long_tags,
							gif_tags: gif_tags
						}
						frames_data.push(single_frame_data);
					}
					var frames_html = template('frames', {
						frames: frames_data,
					});
					var container = document.createElement('div');
					container.innerHTML = frames_html;
					document.getElementById("frames-box").appendChild(container);
					refresh_src();

					if (objs.length == 20) {
						_this.endPullupToRefresh(false);
					} else {
						_this.endPullupToRefresh(true);
						_this.disablePullupToRefresh();
					}
				});
			}
		}
	}
});

var shares = {};
mui.plusReady(function() {
	console.log('plus');
	plus.nativeUI.showWaiting();
	screen_width = plus.screen.resolutionWidth;
	var self = plus.webview.currentWebview();
	topic_id = self.topic_id;
	var storage_key = 'topic_frames_' + topic_id;
	if (storage_key in storage) {
		var frames_data = JSON.parse(storage[storage_key]);
		var frames_html = template('frames', {
			frames: frames_data,
		});
		document.getElementById("frames-box").innerHTML = frames_html;
		setTimeout(function() {
			plus.nativeUI.closeWaiting();
		}, 200);
	}

	var topic_key = 'topic_meta_' + topic_id;
	if (topic_key in storage) {
		var topic_meta = JSON.parse(storage[topic_key]);
		var header_html = template('header-tpl', topic_meta);
		document.getElementById("header").innerHTML = header_html;
	}

	var topic = new Topic();
	topic.id = topic_id;
	topic.fetch().then(function(topic) {
		topic_name = topic.get('name');
		var source_counter = JSON.parse(topic.get('sourceCounter'));
		var sources = [];
		var counts = [];
		for (var source in source_counter) {
			sources.push(source);
			counts.push(source_counter[source]);
		}
		var topic_meta = {
			'cover': topic.get('coverStandard'),
			'name': topic.get('name'),
			'description': topic.get('description'),
			'sources': sources,
			'counts': counts,
			'screen_width': screen_width
		};

		if (!(topic_key in storage)) {
			var header_html = template('header-tpl', topic_meta);
			document.getElementById("header").innerHTML = header_html;
		}
		storage[topic_key] = JSON.stringify(topic_meta);
	});

	var frame_query = new AV.Query(Frame);
	frame_query.equalTo('topic', topic);
	frame_query.ascending('index');
	frame_query.addDescending('recCounter');
	frame_query.addDescending('createdAt');
	frame_query.limit(20);
	frame_query.find().then(function(objs) {
		current_size = objs.length;
		var frames_data = [];
		for (var i = 0; i < objs.length; i++) {
			var meta_data = JSON.parse(objs[i].get('metaDataV2'));
			var title = objs[i].get('head');
			if (title == null || title == undefined) {
				title = meta_data.title
			}

			var text = objs[i].get('content');
			if (text == null || text == undefined) {
				text = meta_data.text;
			}

			var content = meta_data.content;
			var imgs = [],
				long_tags = [],
				gif_tags = [];
			var video_covers = [];
			var cover_width = null,
				cover_height = null;
			for (var j = 0; j < content.length; j++) {
				if (content[j].type == 'photo' || content[j].type == 'gif') {
					var img_url = content[j].upyunUrl;
					imgs.push(img_url);
					long_tags.push(content[j].rawHeight / content[j].rawWidth > 2);
					gif_tags.push(content[j].type == 'gif');
				} else if (content[j].type == 'video') {
					var img_url = content[j].coverUrl;
					video_covers.push(img_url);
				}
			}
			var cover = objs[i].get('coverUrl');

			var is_long = long_tags.length > 0 ? long_tags[0] : false;
			if (cover == null || cover == undefined || cover == '') {
				if (imgs.length > 0) {
					cover = imgs[0];
				} else if (video_covers.length > 0) {
					cover = video_covers[0];
				}
			}

			var single_frame_data = {
				width: screen_width,
				id: objs[i].id,
				style: objs[i].get('style'),
				url: objs[i].get('url'),
				title: title,
				author: objs[i].get('author'),
				text: text,
				rec: objs[i].get('title'),
				rec_count: objs[i].get('recCounter'),
				cover: cover,
				is_long: is_long,
				imgs: imgs,
				meta_data: meta_data,
				liked: (objs[i].id in rec_dict),
				long_tags: long_tags,
				gif_tags: gif_tags
			}
			frames_data.push(single_frame_data);
		}

		if (!(storage_key in storage)) {
			var frames_html = template('frames', {
				frames: frames_data,
			});
			document.getElementById("frames-box").innerHTML = frames_html;
			//mui.previewImage();
			setTimeout(function() {
				plus.nativeUI.closeWaiting();
			}, 200);
		}
		storage[storage_key] = JSON.stringify(frames_data);
		refresh_src();
	}, function(error) {
		alert(error.message);
	});

	//领取徽章信息
	var badge;
	var query = new AV.Query('Topic');
	query.include("badge");
	query.get(self.topic_id, {
		success: function(topic) {
			badge = topic.get("badge");
			if (badge) {
				var badge_data = {
					name: badge.get("name"),
					pic_active: badge.get("picActive"),
					info: badge.get("info")
				}
				var badge_html = template('badge-info-tp1', {
					badge: badge_data,
				});
				document.getElementById("badge-info").innerHTML = badge_html;
				document.getElementById("get-badge-btn").src = badge.get("picActive");
				document.getElementById("get-badge-btn").style.display = "block";
				
				var user = AV.User.current();
				if (user) {
					var badges = user.relation("badges")
					badges.query().find({
  						success: function(list) {
    							for (var i=0; i<list.length; i++) {
    								if (badge.id == list[i].id) {
    									storage["lottery_" + topic_id] = "已领取";
    								}
    							}
  						}
					});
					mui('body').on('tap', '#get-badge', function() {
						storage["lottery_" + topic_id] = "已领取";
						badges.add(badge);
						user.save();
						document.getElementById("get-gift-info").style.display = "block";
						document.getElementById("get-badge-info").style.display = "none";
					});
				}
			} else {
				document.getElementById("get-badge-btn").remove();
			}
		},
		error: function(error) {
			// 失败了.
			document.getElementById("get-badge-btn").remove();
		}
	});

	refresh_src();
	//设置全屏模式
	plus.navigator.setFullscreen(true);
	plus.webview.currentWebview().addEventListener("close", function(e) {
		plus.navigator.setFullscreen(false);
	});

	//搞定分享列表
	plus.share.getServices(function(s) {
		if (s && s.length > 0) {
			for (var i = 0; i < s.length; i++) {
				var t = s[i];
				//使用id作为key
				shares[t.id] = t;
				console.log(i + ":" + t.id);
			}
		}
	}, function() {
		console.log("获取分享服务列表失败");
	});
});

mui('#frames-box').on('tap', '.frame .author', function(e) {
	e.stopPropagation();
	var url = this.getAttribute('data-url');
	plus.nativeUI.confirm('是否前往原页面浏览？', function(e) {
		if (e.index == 1) {
			plus.runtime.openURL(url, function() {
				console.log('error in open origin url');
			});
		}
	}, '饭盒', ['再看会儿', '去浏览']);
});

mui('#frames-box').on('tap', '.frame.standard,.frame.photos,.frame.card .info,.frame.nine, .frame.simple', function() {
	var fid = this.getAttribute('data-id');
	mui.openWindow({
		id: 'frame',
		url: 'frame.html',
		styles: {
			top: 0,
			bottom: 0,
			bounce: 'vertical',
		},
		extras: {
			frame_id: fid,
		},
		show: {
			autoShow: true,
			aniShow: 'pop-in',
			duration: 300,
		},
		waiting: {
			autoShow: false,
		}
	});
});

mui('#frames-box').on('tap', '.frame.nine .imgs img,.frame.photos .imgs img', function(e) {
	//e.stopPropagation();
});

mui('body').on('tap', '.frame.card .cover', function(e) {
	e.stopPropagation();
	var id = this.getAttribute('data-id');
	var video = document.getElementById("video-" + id);
	var video_url = video.src;
	if (plus.networkinfo.getCurrentType() > 3) {
		plus.nativeUI.confirm('饭盒喵检测您正在移动网络下，播放视频需要大量流量喂喵', function(e) {
			if (e.index == 0) {
				if (plus && video_url) {
					if (mui.os.ios) {
						plus.nativeUI.showWaiting("加载链接中", {
							modal: false
						});
						video.onplay = function() {
							plus.nativeUI.closeWaiting();
						};
						video.onclose = function() {
							plus.nativeUI.closeWaiting();
						};
						video.play();
					} else {
						var Intent = plus.android.importClass("android.content.Intent");
						var Uri = plus.android.importClass("android.net.Uri");
						var main = plus.android.runtimeMainActivity();
						var intent = new Intent(Intent.ACTION_VIEW);
						var uri = Uri.parse(video_url);
						intent.setDataAndType(uri, "video/*");
						main.startActivity(intent);
					}
				} else {
					mui.toast("链接可能失效，饭盒喵会尽快处理！");
				}
			}
		}, '确定播放？', ['继续观看', '等会再看']);
	} else {
		if (plus && video_url) {
			if (mui.os.ios) {
				plus.nativeUI.showWaiting("加载链接中", {
					modal: false
				});
				video.onplay = function() {
					plus.nativeUI.closeWaiting();
				};
				video.onclose = function() {
					plus.nativeUI.closeWaiting();
				};
				video.play();
			} else {
				var Intent = plus.android.importClass("android.content.Intent");
				var Uri = plus.android.importClass("android.net.Uri");
				var main = plus.android.runtimeMainActivity();
				var intent = new Intent(Intent.ACTION_VIEW);
				var uri = Uri.parse(video_url);
				intent.setDataAndType(uri, "video/*");
				main.startActivity(intent);
			}
		} else {
			mui.toast("链接可能失效，饭盒喵会尽快处理！");
		}
	}
});

mui('#frames-box').on('tap', '.collect .text', function(e) {
	e.stopPropagation();
	var user = AV.User.current();
	if (user) {
		if (hasClass(this, 'like')) {
			mui.toast('已经收藏');
			return;
		}
		collect(this);
		var new_rec = new Recommendation();
		var frame = new Frame();
		frame.id = this.getAttribute('data-id');
		var topic = new Topic();
		topic.id = topic_id;
		new_rec.set('user', user);
		new_rec.set('frame', frame);
		new_rec.set('topic', topic);
		new_rec.save().then(function(rec) {
			mui.toast('收藏成功');
			//记录已经收藏
			if (!storage["lottery_" + topic_id]) {
				storage["lottery_" + topic_id] = "已收藏";
			}
		}, function(error) {

		});
	} else {
		if (plus) {
			plus.nativeUI.confirm('需要登录才能收藏呢', function(e) {
				if (e.index == 1) {
					var index_view = plus.webview.getLaunchWebview();
					index_view.evalJS('switch_view("collect")');
					plus.webview.currentWebview().close();
				}
			}, '登录确认', ['再看会儿', '去登录']);
		}
	}
});

var is_hide = false;
mui('body').on('tap', '#share-btn', function() {
	if (!is_hide) {
		mui('#share').popover('toggle');
	}
});

mui('body').on('tap', '#get-badge-btn', function() {
	if (!is_hide) {
		if (storage["lottery_" + topic_id] == "已收藏") {
			document.getElementById("get-badge").style.display = "block";
			document.getElementById("get-no-badge").style.display = "none";
			document.getElementById("get-gift-info").style.display = "none";
			document.getElementById("get-badge-info").style.display = "block";
		}
		if (storage["lottery_" + topic_id] == "已领取") {
			document.getElementById("get-gift-info").style.display = "block";
			document.getElementById("get-badge-info").style.display = "none";
		}
		mui('#badge').popover('toggle');
	}
});

mui('body').on('tap', '#get-gift', function() {
	mui.openWindow({
		id: 'gift',
		url: 'gift.html',
		styles: {
			top: 0,
			bottom: 0,
			bounce: "none",
		},
		show: {
			autoShow: true,
		},
		waiting: {
			autoShow: true,
			title: "校验徽章中"
		}
	});
});

//document.body.addEventListener("dragup", function(e) {
//	if (!is_hide) {
//		var eles = document.getElementsByClassName('down-hide');
//		for (var i = 0; i < eles.length; i++) {
//			removeClass(eles[i], 'fadein');
//			addClass(eles[i], 'fadeout');
//		}
//		is_hide = true;
//		removeClass(mui('#back-btn')[0], 'mui-action-back');
//	}
//}, false);
//
//document.body.addEventListener("dragdown", function(e) {
//	if (is_hide) {
//		var eles = document.getElementsByClassName('down-hide');
//		for (var i = 0; i < eles.length; i++) {
//			removeClass(eles[i], 'fadeout');
//			addClass(eles[i], 'fadein');
//		}
//		is_hide = false;
//		addClass(mui('#back-btn')[0], 'mui-action-back');
//	}
//}, false);

mui('#share').on('tap', 'img', function() {
	//DQ：Maybe 提前缓存好？
	var id = this.getAttribute('data-id');
	var type = this.getAttribute('data-type');
	var topic = new Topic();
	console.log(self.topic_id);
	topic.id = self.topic_id;
	topic.fetch().then(function(t) {
		var msg = {};
		//TODO: 微博的文案需要单独考虑
		msg.title = t.get("name");
		msg.content = t.get("description");
		msg.href = "http://t.fanheapp.com/app_topic/" + topic_id;
		msg.thumbs = ["_www/img/miao_120.png"]

		console.log(JSON.stringify(msg));

		if (type == "link") {
			mui('#share').popover('toggle');
			//TODO
			mui.toast("链接已复制到剪贴板");
			return;
		}

		if (type == "weixin-session") {
			msg.extra = {
				scene: "WXSceneSession"
			}
		}
		if (type == "weixin-timeline") {
			msg.extra = {
				scene: "WXSceneTimeline"
			}
		}
		var share = shares[id];
		if (share) {
			if (share.authenticated) {
				console.log("正在分享到" + share.description);
				share.send(msg, function() {
					mui('#share').popover('toggle');
					mui.toast("分享到" + share.description + "成功");
				}, function(e) {
					mui('#share').popover('toggle');
					mui.toast("分享到" + share.description + "失败");
					console.log("分享到\"" + share.description + "\"失败: " + e.code + " - " + e.message);
				});
			} else {
				share.authorize(function() {
					share.send(msg, function() {
						mui('#share').popover('toggle');
						mui.toast("分享到" + share.description + "成功！ ");
					}, function(e) {
						mui('#share').popover('toggle');
						mui.toast("分享到" + share.description + "失败");
						console.log("分享到\"" + share.description + "\"失败: " + e.code + " - " + e.message);
					});
				}, function(e) {
					mui('#share').popover('toggle');
					mui.toast("认证授权失败" + e.message);
					console.log("认证授权失败：" + e.code + " - " + e.message);
				});
			}
		} else {
			mui.toast("无法获取分享服务");
		}
	}, function(error) {
		console.log('error when fetch almanac to share');
	});
});